package com.robusta.cityuate.services;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.robusta.cityuate.R;
import com.robusta.cityuate.activities.OfferingCreateEditActivity;
import com.robusta.cityuate.activities.SpotCreateEditActivity;
import com.robusta.cityuate.objects.Comment;
import com.robusta.cityuate.objects.Spot;
import com.robusta.cityuate.utils.ConnectionUtils;

public class CommentonSpotService extends HTTPService {

	private static final String REQUEST_URL = "/comments";
	private static final String SPOTS_URL = "/spots/";
	private static final String TAG = CommentonSpotService.class.getName();
	private Context mContext = this;
	private boolean isEdit;

	@Override
	protected void onResponse() {
		switch (responseStatusCode) {
		
		case HttpStatus.SC_NO_CONTENT: {// successful comment

			// remove connection from shared pref
			ConnectionUtils.setDisconnecting(mContext, true, assignedFilter,
					null);
			Intent createOfferingUIupdate = new Intent(assignedFilter);
			// update UI if active
			createOfferingUIupdate.putExtra(RESUlT, true);
			// Log.d(TAG, "Success Token " + token);
			sendBroadcast(createOfferingUIupdate);
			break;
		}
		case HttpStatus.SC_NOT_FOUND: {
			onNoResponse(getString(R.string.spot_not_found));
			return;
		}
		case HttpStatus.SC_UNPROCESSABLE_ENTITY: {
			// extract the message
			JSONObject responseMsg;
			String msg = "";
			try {
				responseMsg = new JSONObject(responseString);
				for (@SuppressWarnings("unchecked")
				Iterator<String> iterator = responseMsg.keys(); iterator
						.hasNext();) {
					String key = (String) iterator.next();
					msg += responseMsg.getString(key) + "\n";
				}
				onNoResponse(msg);
			} catch (JSONException e) {
				e.printStackTrace();

			}
		}
		}

	}

	@Override
	protected void onNoResponse(String msg) {
		// remove connection from shared pref keeping result and reason
		ConnectionUtils.setDisconnecting(mContext, false, assignedFilter, msg);
		// update UI if active
		Intent createOfferingUIupdate = new Intent(assignedFilter);
		createOfferingUIupdate.putExtra(RESUlT, false);
		sendOrderedBroadcast(createOfferingUIupdate, null);

	}

	@Override
	protected HttpRequestBase initRequest() {
		isEdit = extras.getBoolean(SpotCreateEditActivity.IS_EDIT, false);
		extras.remove(OfferingCreateEditActivity.IS_EDIT);
		Spot spot = (Spot) extras.getSerializable(Spot.SPOT);
		extras.remove(Spot.SPOT);
		try {
			if (!isEdit) {

				HttpPost req = new HttpPost(API_URL + SPOTS_URL + spot.getId()
						+ REQUEST_URL);
				req.setEntity(createPostBody());			
				return req;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;

	}

	private HttpEntity createPostBody() throws UnsupportedEncodingException {
		// Creating Body
		JSONObject bodyData = new JSONObject();
		JSONObject offer = new JSONObject();
		try {
			if (extras != null) {

				Set<String> extrasKeys = extras.keySet();
				if (!extrasKeys.isEmpty()) {

					for (String key : extrasKeys)
						try {
							bodyData.put(key, extras.get(key).toString());
						} catch (JSONException e) {
							e.printStackTrace();
						}
				}
			}

			offer.put(Comment.COMMENT, bodyData);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		Log.e(TAG, offer.toString());
		return new ByteArrayEntity(offer.toString().getBytes("UTF-8"));

	}
}
